//https://blog.csdn.net/zl1zl2zl3/article/details/81357146
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Icon,
    Button,
    message,
} from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './ProUserGroupList.less';

import UserGroupModel from './ProAssignUserByGroup';//分配用户
import StandardTableGroup from './ProGroupList';//用户组列表
import StandardTableUser from './ProUserList';//用户列表
import {getValue} from '@/utils/globalcommon';
const FormItem = Form.Item;

/* eslint react/no-multi-comp:0 */
@connect(({ prousergroup, loading }) => ({
  prousergroup,
  loading: loading.models.prousergroup,
}))

@Form.create()
class ProUserGroupList extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    viewModalVisible: false,
    userGroupVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    updateFormValues: {},
    viewFormValues: {},
    groupId: [],
    userId: []
  };

  columns = [

    {
      title: '用户名',
      dataIndex: 'user_name',
    },
    {
      title: '用户名称',
      dataIndex: 'user_name_cn',
    },
    {
      title: '用户密码',
      dataIndex: 'password',
    },
    {
      title: '手机号码',
      dataIndex: 'phone',
    },
  ];

  columnGroup = [

    {
      title: '组名',
      dataIndex: 'group_name',
      key: 'group_name',
    }
    
  ];


  componentDidMount() {
    this.reloadTableList();
  }

  reloadTableList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'prousergroup/query_page_for_progroup',
    });
  }

  handleStandardTableChangeGroup = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'prousergroup/query_page_for_progroup',
      payload: params,
    });
  };
  
  handleStandardTableChangeUser = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,groupId } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
      group_id: groupId,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'prousergroup/get_page_for_user_by_groupid',
      payload: params,
    });
  };

  previewItem = id => {
    router.push(`/profile/basic/${id}`);
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'prousergroup/query_page_for_progroup',
      payload: {},
    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };


  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };


  handleSelectUserByGroupId = rows => {
    const groupArray = new Array();
    const { dispatch } = this.props;
    rows.map(item => {
      groupArray.push(item.group_id)
      return groupArray
    })
    this.setState({
      selectedRows: rows,
      groupId: groupArray
    });
    dispatch({
      type: 'prousergroup/get_page_for_user_by_groupid',
      payload: {
        group_id: groupArray,
      }
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'prousergroup/query_page_for_progroup',
        payload: values,
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      updateFormValues: record || {},
    });
  };

  handleViewModalVisible = (flag, record) => {
    this.setState({
      viewModalVisible: !!flag,
      viewFormValues: record || {},
    });
  };

  handleUserGroupVisible = flag => {
    this.setState({
      userGroupVisible: !!flag,
    });
  };

  handleUserList = (flag) => {
    const { dispatch } = this.props;
    const { groupId } = this.state;
    if (!groupId || groupId.length == 0) {
      message.warning("请选择要授权的组!!!");
      return false;
    }
    dispatch({
      type: 'prousergroup/query_page_for_prouserchild',
    });

    dispatch({
      type: 'prousergroup/get_selected_prouser_by_groupid',
      payload: {
        group_id: groupId
      }
    });
    this.handleUserGroupVisible(flag);
  };

  handleUserGroupConnect = userId => {
    const { groupId } = this.state;
    const userGroup = new Array();
    const { dispatch } = this.props;
    if (!groupId || groupId.length == 0) {
      message.warning("请选择要授权的组!!!");
      return false;
    }
    const groupArray = new Array();
    for (let i = 0; i < groupId.length; i++) {
      groupArray.push({
        id: groupId[i]
      })
      for (let j = 0; j < userId.length; j++) {
        userGroup.push({
          group_id: groupId[i],
          user_id: userId[j],
        })
      }
    }
    dispatch({
      type: 'prousergroup/insert_batch_for_prousergroup',
      payload: {
        groupids: groupArray,
        groupids_userids: userGroup
      }
    });
    message.success('授权成功');
    this.handleUserGroupVisible();
  };

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
        <Col md={8} sm={24}>
              <FormItem label="组名">
              {getFieldDecorator('group_name')(<Input placeholder="请输入" />)}
          </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
        <div style={{ marginBottom: 24 }}>
          <Button type="primary" htmlType="submit">
              查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                收起 <Icon type="up" />
              </a>
            </div>
        </div>
        </Form>
    );
  }
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
        <Col md={8} sm={24}>
            <FormItem label="组名">
                {getFieldDecorator('group_name')(<Input placeholder="请输入" />)}
          </FormItem>
        </Col>
          <Col md={8} sm={24}>
              <span className={styles.submitButtons}>
                <Button type="primary" htmlType="submit">
                查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <Icon type="down" />
                </a>
              </span>
          </Col>
        </Row>
        </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const {
      prousergroup: { data, group, userChild, userSelect },
      loading,
    } = this.props;

    const { selectedRows, modalVisible, updateModalVisible, viewModalVisible, updateFormValues, viewFormValues, userGroupVisible } = this.state;

    const userGroupMethods = {
      handleUserGroupVisible: this.handleUserGroupVisible,
      handleUserGroupConnect: this.handleUserGroupConnect,
      userSelect: userSelect
    };
    return (
      <PageHeaderWrapper title="分组用户信息列表">
            <Card bordered={false}>
            <div className={styles.proUserGrouptableList}>
            <div className={styles.proUserGrouptableListForm}>{this.renderForm()}</div>
            <div className={styles.proUserGrouptableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleUserList(true)}>
      分配用户
        </Button>
    </div>
        <StandardTableGroup
        rowKey={"group_id"}
        selectedRows={selectedRows}
        loading={loading}
        data={group}
        columns={this.columnGroup}
        onSelectRow={this.handleSelectUserByGroupId}
        onChange={this.handleStandardTableChangeGroup}
        />
        <StandardTableUser
        rowKey={"user_id"}
        selectedRows={selectedRows}
        loading={loading}
        data={data}
        columns={this.columns}
        onSelectRow={this.handleSelectRows}
        onChange={this.handleStandardTableChangeUser}
        />
        </div>
        </Card>
    <UserGroupModel {...userGroupMethods} userGroupVisible={ userGroupVisible } userChild={ userChild }/>

    </PageHeaderWrapper>
    );
  }
}

export default ProUserGroupList;
